import { codeToHtml } from 'shiki'

/**
 * 正则表达式匹配 http:// 或 https:// 开头的 URL
 * @returns {string|null}
 */
function extractUrlFromString(str) {
  const urlRegex = /https?:\/\/[^\s]+/;
  const match = str.match(urlRegex);
  return match ? match[0] : null;
}
/**
 * 获取调用者文件路径
 * @returns {string|null}
 */
function getCallerPath() {
  const stack = new Error().stack

  if (!stack) return null

  // 解析调用栈，找到调用useCode的组件路径
  const stackLines = stack.split('\n')
  // 通常调用链是：Error -> getCallerPath -> useCode -> 实际调用组件
  const callerLine = stackLines[4] || stackLines[3] || stackLines[2]

  const path = extractUrlFromString(callerLine)

  return path
}

/**
 * 解析基于调用者的正确路径
 * @param {string} rawPath
 * @returns {string}
 */
function resolveRelativePath(rawPath) {
  const callerPath = getCallerPath()
  if (!callerPath) return rawPath

  // 在浏览器环境中模拟path.resolve
  const segments = [
    callerPath.split('/').slice(0, -1).join('/'), // 调用者目录
    ...rawPath.split('/')
  ]

  const resolved = []
  for (const segment of segments.flatMap(s => s.split('/'))) {
    if (segment === '..') {
      resolved.pop()
    } else if (segment !== '.' && segment !== '') {
      resolved.push(segment)
    }
  }
  return resolved.join('/')
}

/**
 * 加载并高亮显示代码文件
 * @param {string} filePath - 支持 ./index.js 或 @/components/example.js
 * @param {object} options - shiki配置
 * @returns {Promise<string>}
 */
export async function useCode(filePath, options = {}) {
  try {

    // 解析路径
    const resolvedPath = filePath.startsWith('@/')
      ? filePath
      : resolveRelativePath(filePath)

    // 添加raw查询参数
    const importPath = `${resolvedPath}?raw`

    console.log(resolvedPath);

    // 动态导入文件内容
    const codeModule = await import(/* @vite-ignore */ importPath)
    const code = codeModule.default
    console.log(code);

    // 自动检测语言类型
    const lang = getLanguageFromPath(filePath)

    // 生成高亮代码
    return await codeToHtml(code, {
      lang,
      theme: 'vitesse-dark',
      ...options
    })
  } catch (error) {
    console.error(`Failed to load code: ${filePath}`, error)
    return `<pre class="shiki-error">Error loading ${filePath}: ${error.message}</pre>`
  }
}

/**
 * 根据文件路径推断语言类型
 * @param {string} filePath
 * @returns {string}
 */
function getLanguageFromPath(filePath) {
  const extension = filePath.split('.').pop().toLowerCase()

  const languageMap = {
    'js': 'javascript',
    'ts': 'typescript',
    'vue': 'vue',
    'html': 'html',
    'css': 'css',
    'scss': 'scss',
    'json': 'json',
    'md': 'markdown'
  }

  return languageMap[extension] || 'text'
}
